﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace UniRlv.Utility.AppLib
{
    public class SerialInDevice:AbtInDevice
    {
        private SerialPort serial;
        private int port;
        private int bd;
        private byte[] recBuff;
        private Parity p;
        private int dataBits;

        public SerialInDevice()
        {
            InitString = "1,9600";
            Prefix = 0;
            Suffix = "\r";
            p = Parity.None;
            dataBits = 8;

            serial = new SerialPort();

            recBuff = new byte[serial.ReadBufferSize+1];
            prcBuff = new List<byte>();

            dataQueue = new Queue<string>();
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <returns></returns>
        public override bool Open()
        {
            if (IsOpen())
            {
                return true;
            } 
            else
            {
                serial.PortName = string.Format("COM{0}", port);
                serial.BaudRate = bd;
                serial.RtsEnable = true;
                serial.DataReceived += serial_DataReceived;
                serial.Encoding = Encoding.GetEncoding("gb2312");
                serial.Parity = p;
                serial.DataBits = dataBits;

                try
                {
                	serial.Open();
                    
                    return true;
                }
                catch (System.Exception ex)
                {
                    ErrorString = ex.Message;
                    return false;
                }
            }
        }

        void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int cnt = serial.Read(recBuff, 0, serial.ReadBufferSize);

            for (int i = 0; i < cnt; i++ )
            {
                prcBuff.Add(recBuff[i]);
            }

            while(ByteProccess())
            {
                SetEvent(null);
            }
        }

        public override bool IsOpen()
        {
            return serial.IsOpen;
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        public override void Close()
        {
            if (serial.IsOpen)
            {
                serial.Close();
            }
        }

        public override void Pause()
        {
            serial.DataReceived -= serial_DataReceived;
            Close();
        }

        public override void Resume()
        {
            //serial.DiscardInBuffer();
            //serial.DiscardOutBuffer();

            try
            {
                serial.Open();
                serial.DiscardInBuffer();
                serial.DiscardOutBuffer();
                prcBuff.Clear();
                dataQueue.Clear();
                serial.DataReceived += serial_DataReceived;
            }
            catch
            {

            }

            
        }

        public override void SendData(byte[] bytes, int len)
        {
            try
            {
                serial.Write(bytes, 0, len);
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
            
        }

        public override string InitString
        {
            get
            {
                return _initString;
            }
            set
            {
                string[] paramStrings = value.Split(',');

                if (paramStrings.Length>1)
                {
                    port = Convert.ToInt32(paramStrings[0]);
                    bd = Convert.ToInt32(paramStrings[1]);

                    _initString = value;
                }

                if (paramStrings.Length > 2)
                {
                    p = (Parity)Convert.ToInt32(paramStrings[2]);
                }

                if (paramStrings.Length > 3)
                {
                    dataBits = Convert.ToInt32(paramStrings[3]);
                }
            }
        }

    }
}
